package com.yh.musicplayer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Message;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.yh.musicplayer.data.Music;
import com.yh.musicplayer.data.MusicList;
import com.yh.musicplayer.data.MusicService;
import com.yh.musicplayer.data.disc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
    //手势识别对象的创建
    private GestureDetector gestureDetector;
    //播放模式常量
    private static final int MODE_RANDOM_PLAY=0;
    private static final int MODE_SINGLE_CYCLE=1;
    private static final int MODE_LIST_CYCLE=2;
    private int playmode;
    //音量控制
    private TextView tv_vol;
    private SeekBar seekBar_vol;
    private LinearLayout linearLayout;

    //专辑图片相关
    public int which_activity;
    private ImageView mImageView;

    //睡眠相关
    private ImageView iv_sleep;
    private Timer timer_sleep;
    private static final boolean NOTSLEEP=false;
    private static final boolean ISSLEEP=true;
    //默认睡眠时间
    private int sleepminute=20;
    //标记是否打开睡眠模式
    private static boolean sleepmode;

    //退出判断
    private static boolean isExit=false;

    //private ImageButton imgBtn_Previous;
    private ImageButton imgBtn_PlayOrPause;
    private ImageButton imgBtn_Stop;
    private ImageButton imgBtn_Next;
    //private ImageButton img_playmode;
    private ListView list;
    private int status;
    //private TextView textView;
    private RelativeLayout root_Layout;
    //广播接收器
    private StatusChangedReceiver receiver;
    //private TextView text_Current;
    //private TextView text_Duration;
    private SeekBar seekBar;
    private Handler seekBarHandler;
    //当前歌曲持续时间和位置，进度条
    private int duration;
    private int time;
    //进度条控制常量
    private static final int PROGRESS_INCREASE=0;
    private static final int PROGRESS_PAUSE=1;
    private static final int PROGRESS_RESET=2;
    //歌曲列表对象
    private ArrayList<Music>musicArrayList;
    private int number=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViews();
        registerListeners();
        initMusicList();
        initListView();
        checkMusicfile();
        initSeekBarHandler();
        duration=0;
        time=0;
        //绑定广播接收器
        bindStatusChangedReceiver();
        startService(new Intent(this, MusicService.class));
        status=MusicService.COMMAND_STOP;

        //要删，默认播放模式是顺序
        playmode=MainActivity.MODE_LIST_CYCLE;
        //默认睡眠模式为关闭
        sleepmode=MainActivity.NOTSLEEP;

        gestureDetector = new GestureDetector(this,this);
        which_activity=1;

    }
    private void bindStatusChangedReceiver(){
        receiver=new StatusChangedReceiver();
        IntentFilter filter=new IntentFilter(MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver,filter);
    }

    //重写onToughEvent
    public boolean onToughEvent(MotionEvent event){
        return gestureDetector.onTouchEvent(event);
    }
    //重写onFling方法
    public boolean onFling(MotionEvent arg0,MotionEvent arg1,float arg2,float arg3){
//        if(arg1.getX()-arg0.getX()>150){
//            Intent intent=new Intent();
//            intent.setClass(MainActivity.this,disc.class);
//            startActivity(intent);
//            overridePendingTransition(R.anim.to_right_enter,R.anim.to_right_exit);
//        }
        return false;
    }
    public boolean dispatchTouchEvent(MotionEvent event){
        if(gestureDetector.onTouchEvent(event)){
            event.setAction(MotionEvent.ACTION_CANCEL);
        }
        return super.dispatchTouchEvent(event);
    }
    private void findViews(){
        //imgBtn_Previous=(ImageButton) findViewById(R.id.imageButton1);
        imgBtn_PlayOrPause=(ImageButton) findViewById(R.id.imageButton2);
       // imgBtn_Stop=(ImageButton) findViewById(R.id.imageButton3);
        //img_playmode=(ImageButton)findViewById(R.id.imageButton3);
        imgBtn_Next=(ImageButton) findViewById(R.id.imageButton4);
        list=(ListView) findViewById(R.id.listView1);
        root_Layout = (RelativeLayout) findViewById(R.id.relativeLayout1);
        //textView=(TextView)findViewById(R.id.textView);
        seekBar=(SeekBar)findViewById(R.id.seekBar1);
        //text_Current=(TextView)findViewById(R.id.textView1);
        //text_Duration=(TextView)findViewById(R.id.textView2);
        tv_vol=(TextView)findViewById(R.id.main_volumeText);
        seekBar_vol=(SeekBar)findViewById(R.id.main_volumebar);
        iv_sleep=(ImageView)findViewById(R.id.main_iv_sleep);
        mImageView=(ImageView)findViewById(R.id.Album_show);
        linearLayout=(LinearLayout)findViewById(R.id.linearLayout1);
    }
    //设置主题
    private void setTheme(String theme){
        if("彩色".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_color);
        }else if("花朵".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_digit_flower);
        }else if("健身妹子3".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.gym_girl);
        }else if("健身妹子1".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_running_dog);
        }else if("冰雪".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_snow);
        }else if("健身妹子2".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_music_girl);
        }else if("朦胧".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_blur);
        }
    }
    //音量控制
    private void audio_Control(){
        //音量管理器
        final AudioManager audioManager=(AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        final int max_progress=audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        seekBar_vol.setMax(max_progress);
        int progress=audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekBar_vol.setProgress(progress);
        tv_vol.setText("音量: "+(progress*100/max_progress)+"%");
        seekBar_vol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tv_vol.setText("音量： "+(progress*100)/(max_progress)+"%");
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,progress,AudioManager.FLAG_PLAY_SOUND);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }
    //双击退出
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int progress;
        switch (keyCode){
            case KeyEvent.KEYCODE_BACK:
                if(which_activity==1){
                    exitByDoubleClick();
                }
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                progress=seekBar_vol.getProgress();
                if(progress!=0)
                    seekBar_vol.setProgress(progress-1);
                return true;
            case KeyEvent.KEYCODE_VOLUME_UP:
                progress=seekBar_vol.getProgress();
                if(progress!=seekBar_vol.getMax())
                    seekBar_vol.setProgress(progress+1);
                return true;
            default:
                break;
        }
        return false;
    }

    private void exitByDoubleClick() {
        Timer timer=null;
        if(isExit==false){
            isExit=true;
            Toast.makeText(this,"再按一次退出程序!",Toast.LENGTH_SHORT).show();
            timer=new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit=false;
                }
            },2000);
        }
        else {
            finish();
            System.exit(0);
        }

    }

    //创建菜单
    public boolean onCreateOptionsMenu(Menu menu){
        this.getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }
    //菜单响应事件
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.menu_theme:
                new android.app.AlertDialog.Builder(this)
                        .setTitle("请选择主题").
                        setItems(R.array.theme,
                                new android.content.DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        String theme = PropertyBean.THEMES[which];
                                        MainActivity.this.setTheme(theme);
                                        PropertyBean property = new PropertyBean(MainActivity.this);
                                        property.setAndSaveTheme(theme);
                                    }
                                }).show();
                break;
            case R.id.menu_about:
                new android.app.AlertDialog.Builder(MainActivity.this)
                        .setTitle("GRacePlayer")
                        .setMessage(R.string.about2).show();
                break;
            case R.id.menu_quit:
                //退出程序
                new android.app.AlertDialog.Builder(this)
                        .setTitle("提示").
                        setMessage(R.string.quit).setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        System.exit(0);
                    }
                }).setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                }).show();
                break;
            //要删
            case R.id.menu_playmode:
                String[] mode=new String[]{"随机播放","单曲循环","列表循环"};
                AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("播放模式");
                builder.setSingleChoiceItems(mode, playmode, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        playmode=which;
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (playmode){
                            case 0:
                                playmode=MainActivity.MODE_RANDOM_PLAY;
                                Toast.makeText(getApplicationContext(),"随机播放",Toast.LENGTH_SHORT).show();
                                break;
                            case 1:
                                playmode=MainActivity.MODE_SINGLE_CYCLE;
                                Toast.makeText(getApplicationContext(),"单曲循环",Toast.LENGTH_SHORT).show();
                                break;
                            case 2:
                                playmode=MainActivity.MODE_LIST_CYCLE;
                                Toast.makeText(getApplicationContext(),"列表循环",Toast.LENGTH_SHORT).show();
                                break;
                            default:
                                break;
                        }
                    }
                });
                builder.show();
                break;
            case R.id.menu_sleep:
                showSleepDialog();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showSleepDialog(){
        final View userview=this.getLayoutInflater().inflate(R.layout.dialog,null);
        final TextView tv_minute=(TextView)userview.findViewById(R.id.dialog_tv);
        final Switch switch1=(Switch)userview.findViewById(R.id.dialog_switch);
        final SeekBar seekBar=(SeekBar)userview.findViewById(R.id.dialog_seekbar);

        tv_minute.setText("睡眠于："+sleepminute+"分钟");
        if(sleepmode==MainActivity.ISSLEEP)switch1.setChecked(true);
        seekBar.setMax(60);
        seekBar.setProgress(sleepminute);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                sleepminute=progress;
                tv_minute.setText("睡眠于:"+sleepminute+"分钟");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                sleepmode=isChecked;
            }
        });
        final TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                System.exit(0);
            }
        };
        //定义对话框以及初始化
        final android.app.AlertDialog.Builder dialog = new android.app.AlertDialog.Builder(this);
        dialog.setTitle("选择睡眠时间(0~60分钟)");
        //设置布局
        dialog.setView(userview);
        //设置取消按钮响应事件
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                arg0.dismiss();
            }
        });
        //设置重置按钮响应时间
        dialog.setNeutralButton("重置", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                if(sleepmode == MainActivity.ISSLEEP)
                {
                    timerTask.cancel();
                    timer_sleep.cancel();
                }
                sleepmode = MainActivity.NOTSLEEP;
                sleepminute = 20;
                iv_sleep.setVisibility(View.INVISIBLE);
            }
        });
        //设置确定按钮响应事件
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                if(sleepmode == MainActivity.ISSLEEP)
                {
                    timer_sleep = new Timer();
                    int time =seekBar.getProgress();
                    //启动任务，time*60*1000毫秒后执行
                    timer_sleep.schedule(timerTask, time*60*1000);
                    iv_sleep.setVisibility(View.VISIBLE);
                }
                else
                {
                    //取消任务
                    timerTask.cancel();
                    if(timer_sleep != null) timer_sleep.cancel();
                    arg0.dismiss();
                    iv_sleep.setVisibility(View.INVISIBLE);
                }
            }
        });
        dialog.show();
    }

    private void registerListeners(){
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setClass(MainActivity.this,disc.class);
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.fragment_slide_up,R.anim.fragment_slide_down);
            }
        });
//        img_playmode.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                switch (playmode){
//                    case 0:
//                        img_playmode.setBackgroundResource(R.drawable.list_recycle);
//                        playmode=MainActivity.MODE_LIST_CYCLE;
//                        Toast.makeText(getApplicationContext(),"列表循环",Toast.LENGTH_SHORT).show();
//                        break;
//                    case 1:
//                        img_playmode.setBackgroundResource(R.drawable.random_play);
//                        playmode=MainActivity.MODE_RANDOM_PLAY;
//                        Toast.makeText(getApplicationContext(),"随机播放",Toast.LENGTH_SHORT).show();
//                        break;
//                    case 2:
//                        img_playmode.setBackgroundResource(R.drawable.single_recycle);
//                        playmode=MainActivity.MODE_SINGLE_CYCLE;
//                        Toast.makeText(getApplicationContext(),"单曲循环",Toast.LENGTH_SHORT).show();
//                        break;
//                    default:
//                        break;
//                }
//            }
//        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(status!=MusicService.STATUS_STOPPED){
                    time=seekBar.getProgress();
                    //text_Current.setText(formatTime(time));
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                }
                if(status==MusicService.STATUS_PLAYING){
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }if(status==MusicService.STATUS_PAUSED){
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }

            }
        });
//        imgBtn_Previous.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                switch (playmode){
//                    case MainActivity.MODE_RANDOM_PLAY:
//                        sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
//                        break;
//                    case MainActivity.MODE_SINGLE_CYCLE:
//                            sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
//                            break;
//                    default:
//                        sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);
//                        break;
//                }
//
//            }
//        });

        imgBtn_PlayOrPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (status){
                    case MusicService.STATUS_PLAYING:
                        sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        break;
                    case MusicService.STATUS_PAUSED:
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        break;
                    case MusicService.STATUS_STOPPED:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                }
            }
        });

//        imgBtn_Stop.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                sendBroadcastOnCommand(MusicService.COMMAND_STOP);
//            }
//        });

        imgBtn_Next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (playmode){
                    case MainActivity.MODE_RANDOM_PLAY:
                        sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
                        break;
                    case MainActivity.MODE_SINGLE_CYCLE:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        break;
                    default:
                        sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                        break;
                }
            }
        });

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                number=position;
                Intent intent=new Intent();
                intent.setClass(MainActivity.this,disc.class);
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.fragment_slide_up,R.anim.fragment_slide_down);
                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);

            }
        });
    }
    private void initMusicList() {
        musicArrayList = MusicList.getMusicList();
        //avoid add music repeatedly
        if (musicArrayList.isEmpty()) {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[]{MediaStore.Audio.Media.TITLE,
                            MediaStore.Audio.Media.DURATION,
                            MediaStore.Audio.Media.ALBUM,
                            MediaStore.Audio.Media.ARTIST,
                            MediaStore.Audio.Media._ID,
                            MediaStore.Audio.Media.DATA,
                            MediaStore.Audio.Media.DISPLAY_NAME,
                            MediaStore.Audio.Media.ALBUM_ID}, null, null,
                    MediaStore.Audio.AudioColumns.TITLE);
            if (mMusicCursor != null) {
                int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
                int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
                int indexDuration = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
                int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);

                //专辑ID获取
                int indexAlbum_id=mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ALBUM_ID);

                for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor.moveToNext()) {
                    String strTitle = mMusicCursor.getString(indexTitle);
                    String strArtist = mMusicCursor.getString(indexArtist);
                    String strTotalTime = mMusicCursor.getString(indexDuration);
                    String strPath = mMusicCursor.getString(indexPath);
                    String strAlbum_id=mMusicCursor.getString(indexAlbum_id);

                    if (strArtist.equals("<unknown>"))
                        strArtist = "无艺术家";
                    Music music = new Music(strTitle, strArtist, strPath, strTotalTime,strAlbum_id);
                    musicArrayList.add(music);
                }
            }
        }
    }

    private void getImage(int id){
        int album_id = id;
        String albumArt = getAlbumArt(album_id);
        Bitmap bm = null;
        if (albumArt == null){
            mImageView.setBackgroundResource(R.drawable.main_play);
        }
        else{
            bm = BitmapFactory.decodeFile(albumArt);
            BitmapDrawable bmpDraw = new BitmapDrawable(bm);
            mImageView.setImageDrawable(bmpDraw);
        }
    }

    private String getAlbumArt(int album_id){
        String mUriAlbums = "content://media/external/audio/albums";
        String[] projection = new String[] { "album_art" };
        Cursor cur = this.getContentResolver().query(Uri.parse(mUriAlbums + "/" + Integer.toString(album_id)),projection, null, null, null);
        String album_art = null;
        if (cur.getCount() > 0 && cur.getColumnCount() > 0){
            cur.moveToNext();
            album_art = cur.getString(0);
        }
        cur.close();
        cur = null;
        return album_art;
    }


    private void initListView() {
        List<Map<String, String>> list_map = new ArrayList<Map<String, String>>();
        HashMap<String, String> map;
        SimpleAdapter simpleAdapter;
        for (Music music : musicArrayList) {
            map = new HashMap<String, String>();
            map.put("musicName", music.getMusicName());
            map.put("musicArtist", music.getMusicArtist());
            list_map.add(map);
        }
        String[] from = new String[] { "musicName", "musicArtist" };
        int[] to = { R.id.listview_tv_title_item, R.id.listview_tv_artist_item };
        simpleAdapter = new SimpleAdapter(this, list_map, R.layout.listview,from, to);
        list.setAdapter(simpleAdapter);
    }
    private void checkMusicfile()
    {
        if (musicArrayList.isEmpty()) {
            imgBtn_Next.setEnabled(false);
            imgBtn_PlayOrPause.setEnabled(false);
//            imgBtn_Previous.setEnabled(false);
            imgBtn_Stop.setEnabled(false);
            Toast.makeText(getApplicationContext(), "当前没有歌曲文件",Toast.LENGTH_SHORT).show();
        } else {
            imgBtn_Next.setEnabled(true);
            imgBtn_PlayOrPause.setEnabled(true);
//            imgBtn_Previous.setEnabled(true);
//            imgBtn_Stop.setEnabled(true);
        }
    }

    //实现启动服务，检查播放状态
    protected void onResume(){
        super.onResume();
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
        PropertyBean property=new PropertyBean(MainActivity.this);
        String theme=property.getTheme();
        setTheme(theme);
        audio_Control();
        //睡眠模式打开时显示图标,关闭时隐藏图标
        if(sleepmode==MainActivity.ISSLEEP)iv_sleep.setVisibility(View.VISIBLE);
        else iv_sleep.setVisibility(View.INVISIBLE);
        which_activity=1;

    }

    private void sendBroadcastOnCommand(int command){
        Intent intent=new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command",command);
        switch (command){
            case MusicService.COMMAND_PLAY:
                intent.putExtra("number",number);
                break;
            case MusicService.COMMAND_SEEK_TO:
                intent.putExtra("time",time);
                break;
            case MusicService.COMMAND_PLAYMODE_CHANGED:
                intent.putExtra("playmode",playmode);
                break;
            case MusicService.COMMAND_PREVIOUS:
            case MusicService.COMMAND_NEXT:
            case MusicService.COMMAND_PAUSE:
            case MusicService.COMMAND_STOP:
            case MusicService.COMMAND_RESUME:
            default:
                break;
        }
        sendBroadcast(intent);
    }

    private void initSeekBarHandler() {
        seekBarHandler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case PROGRESS_INCREASE:
                        if (seekBar.getProgress() < duration) {
                            //进度条前进一秒
                            seekBar.setProgress(time);
                            //seekBar.incrementProgressBy(1000);
                            seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            //修改显示当前进度的文本
                            //text_Current.setText(formatTime(time));
                            time += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        //重置进度条画面
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        //text_Current.setText("00:00");
                        break;
                }
            }
        };
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    //内部类，用来更新播放器状态
    class StatusChangedReceiver extends BroadcastReceiver{
        public void onReceive(Context context, Intent intent){
            String musicName=intent.getStringExtra("musicName");
            String musicArtist=intent.getStringExtra("musicArtist");
            //获取播放器状态
            status=intent.getIntExtra("status",-1);
            String Album_id=intent.getStringExtra("musicAlbum_id");
            switch (status){
                case MusicService.STATUS_PLAYING:
                    seekBarHandler.removeMessages(PROGRESS_INCREASE);
                    playmode=intent.getIntExtra("playmode",0);

                    time=intent.getIntExtra("time",0);
                    duration=intent.getIntExtra("duration",0);
                    number=intent.getIntExtra("number",number);
                    list.setSelection(number);//歌多了之后显示在最上面
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.main_stop);
                    MainActivity.this.setTitle("正在播放:"+musicName+"-"+musicArtist);
                    getImage(Integer.valueOf(Album_id).intValue());
                    break;
                case MusicService.STATUS_PAUSED:
                    time=intent.getIntExtra("time",0);
                    playmode=intent.getIntExtra("playmode",0);
                    duration=intent.getIntExtra("duration",0);
                    number=intent.getIntExtra("number",number);
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.main_play);
                    MainActivity.this.setTitle("已暂停:"+musicName+"-"+musicArtist);
                    getImage(Integer.valueOf(Album_id).intValue());
                    break;
                case MusicService.STATUS_STOPPED:
                    time=0;
                    duration=0;
                    //text_Current.setText(formatTime(time));
                    //text_Duration.setText(formatTime(duration));
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.main_play);
                    MainActivity.this.setTitle("");
                    break;
                case MusicService.STATUS_COMPLETED:
                    number=intent.getIntExtra("number",0);
                    if(playmode==MainActivity.MODE_RANDOM_PLAY)
                        sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
                    else if(playmode==MainActivity.MODE_SINGLE_CYCLE)
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    else if(playmode==MainActivity.MODE_LIST_CYCLE){
                        if(number==MusicList.getMusicList().size()-1){
                            number=0;
                            sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        }
                        else
                            sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                    }

                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle("");
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.main_play);
                    break;
                default:
                    break;
            }
        }
    }
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if (status == MusicService.STATUS_STOPPED) {
            stopService(new Intent(this, MusicService.class));
        }
        super.onDestroy();
    }

}




